<template>
	<web-view ref="webview" class="y-flex-1" src="/hybrid/html/CodeReader.html" @onPostMessage="handleMessage"></web-view>
</template>

<script>
	import { getEl } from '@/assets/js/util.js'
	export default {
		props: {
			//内容
			text: {
				type: String,
				default: ''
			},
			//模式 html-html文本 js-js文本 css-css文本
			mode: {
				type: String,
				default: 'html'
			},
			//主题色 light-亮色 dark-暗色
			theme: {
				type: String,
				default: 'light'
			}
		},
		data () {
			return {
				ready: false//webview是否加载完毕
			}
		},
		mounted() {
			this.setTheme(this.theme)
		},
		methods: {
			handleMessage (e) {
				e.detail.data.forEach(item => {
					if ( item.ready ) {
						this.ready = true
						this.setTheme(this.theme)
						if ( this.text ) this.setValue(this.text)
					}
				})
			},
			//重置内容
			setValue (value) {
				this.$refs.webview && this.$refs.webview.evalJS(`setValue('${JSON.stringify(value.replace(/\'/g, '&aposync;'))}', '${this.mode}');`)
			},
			//设置主题
			setTheme (theme) {
				this.$refs.webview && this.$refs.webview.evalJS(`setTheme('${theme}');`)
			}
		},
		watch: {
			text (newVal) {
				if ( this.ready ) this.setValue(newVal)
			},
			mode (newVal) {
				if ( this.ready ) this.setValue(this.value)
			},
			theme (newVal) {
				this.setTheme(newVal)
			}
		}
	}
</script>

<style>
</style>